//
// Created by 215609 on 2024/8/14.
//

#include "AAudioRender.h"
AAudioRender::AAudioRender(){

}

aaudio_data_callback_result_t AAudioRender::dataCallback(AAudioStream *stream,void *audioData,
        int32_t numFrames){
    LOGCATE("RenderAudioFrame1 AAudioRender=%d",numFrames);
    auto size=numFrames * 2 * (mFormat == AAUDIO_FORMAT_PCM_I16 ? 2 : 1);
    LOGCATE("RenderAudioFrame1 AAudioRender size=%d",size);
    return AAUDIO_CALLBACK_RESULT_CONTINUE;
}
aaudio_data_callback_result_t dataCallback(AAudioStream *stream, void *userData,
                                           void *audioData, int32_t numFrames) {

    AAudioRender *audioEngine = reinterpret_cast<AAudioRender *>(userData);

    return audioEngine->dataCallback(stream,audioData,numFrames);



}

void AAudioRender::Init() {
    LOGCATE("player1 AAudioRender32 Init");
    aaudio_result_t result= AAudio_createStreamBuilder(&builder);
    LOGCATE("player2  AAudioRender32 Init",result);
    if (result!=AAUDIO_OK){
        LOGCATE("player3 AAudioRender32 result",result);
    }

    LOGCATE("player4 AAudioRender32 Init11=%d",result);
//    AAudioStreamBuilder_setDeviceId(builder, AAUDIO_UNSPECIFIED);
    AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_OUTPUT);
    AAudioStreamBuilder_setSharingMode(builder, AAUDIO_SHARING_MODE_EXCLUSIVE);
    LOGCATE("player IAAudioStreamBuilder_setSharingMode11=%d",result);
    AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_I16);
    AAudioStreamBuilder_setChannelCount(builder, 2);
    //独占 AAUDIO_SHARING_MODE_SHARED
    //AAUDIO_PERFORMANCE_MODE_LOW_LATENCY 更注重延迟
    AAudioStreamBuilder_setPerformanceMode(builder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY);
    AAudioStreamBuilder_setDataCallback(builder, ::dataCallback, this);

//    AAudioStream_setBufferSizeInFrames(mAudioStream,2);

    result= AAudioStreamBuilder_openStream(builder,&mAudioStream);
    if (result==AAUDIO_OK&&mAudioStream!=nullptr){
        if (mFormat!= AAudioStream_getFormat(mAudioStream)){
            //获取帧大小最好的性能
            int framesPerBurst = AAudioStream_getFramesPerBurst(mAudioStream);
            AAudioStream_setBufferSizeInFrames(mAudioStream, framesPerBurst);
        }
    }


    AAudioStreamBuilder_delete(builder);

    StartRender();
//    &stream.AAudioStreamBuilder_setDeviceId();
//    *stream->AAudioStream_getDeviceId();


}


void AAudioRender::UnInit() {
    aaudio_result_t result = AAudioStream_requestStop(mAudioStream);
    if (mAudioStream) {
        AAudioStream_close(mAudioStream);
    }


}

void AAudioRender::ClearAudioCache() {


}

void AAudioRender::StartRender() {
    aaudio_result_t result;
    result=AAudioStream_requestStart(mAudioStream);


}


void AAudioRender::RenderAudioFrame(uint8_t *pData, int dataSize) {
//    realloc()
    LOGCATE("RenderAudioFrame1 aaudio=%d",dataSize);


}



